package com.apes.fa.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fa.model.FaAssetScrap;
import com.apes.fa.model.FaAssetScrapItem;
import com.apes.fa.model.FaCard;
import com.apes.fa.respository.FaAssetScrapRepository;
import com.apes.fa.respository.FaCardRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.IntStream;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fa.service
 * @ClassName: FaAssetScrapService
 * @Author: PengZiFeng
 * @Description: 资产报废毁损
 * @CreateTime: 2021-09-22 11:45
 * @Version: 1.0
 */
@Service("faAssetScrapService")
public class FaAssetScrapService extends DomainService {

    @Autowired
    private FaAssetScrapRepository faAssetScrapRepository;
    @Autowired
    private FaCardAccountService faCardAccountService;
    @Autowired
    private FaCardRepository faCardRepository;


    /**
     * 保存
     */
    public FaAssetScrap save(SimpleRequest request){

        FaAssetScrap faAssetScrap = request.getO(FaAssetScrap.class);
        faAssetScrap.setState("create");
        //可以报废的卡片条件
        List<FaAssetScrapItem> faAssetScrapItems = faAssetScrap.getFaAssetScrapItems();
        for (FaAssetScrapItem faAssetScrapItem : faAssetScrapItems) {
            FaCard faCard = faAssetScrapItem.getFaCard();
            if(faCard == null) throw new RuntimeException("请添加资产卡片明细");
            String id = faCard.getId();
            String status = faCard.getFaStatus();
            if(!(status.equals("1") || status.equals("2") || status.equals("3"))){
                throw new RuntimeException(id+"该卡片不可报废");
            }
            faAssetScrapItem.setDecreaseReason("报废");
        }
        return faAssetScrapRepository.saveAndFlush(faAssetScrap);


    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request){
        FaAssetScrap faAssetScrap = request.getO(FaAssetScrap.class);
        faAssetScrapRepository.delete(faAssetScrap);
        return "删除成功！";
    }

    /**
     * 审核并生成报废卡片账
     */
    public FaAssetScrap approve(SimpleRequest request){

        FaAssetScrap faAssetScrap = request.getO(FaAssetScrap.class);
        faAssetScrap.setState("approve");
        faAssetScrap.setApproveDate(new Date());
        faAssetScrap.setApproveUid(this.getPerson(request));
        List<FaAssetScrapItem> faAssetScrapItems = faAssetScrap.getFaAssetScrapItems();
        for (FaAssetScrapItem faAssetScrapItem : faAssetScrapItems) {
            Optional<FaCard> optional = faCardRepository.findById(faAssetScrapItem.getFaCard().getId());
            FaCard faCard = optional.get();
            faCardAccountService.scrap(faAssetScrap,faCard,request);
        }
        return faAssetScrapRepository.saveAndFlush(faAssetScrap);

    }

    /**
     * 导入
     */
    public JSONObject importInfo(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field = (JSONArray) request.get("data");
        JSONObject exclObject = new JSONObject();                  //返回值

        JSONArray exclArr = new JSONArray();            //行内容
        JSONArray headerName = new JSONArray();         //头部
        JSONArray fieldName = new JSONArray();          //field
        for (Object o : field) {
            JSONObject webTab = (JSONObject) o;
            headerName.add(webTab.get("name"));
            fieldName.add(webTab.get("field"));
        }

        //获取model
        JSONObject model = (JSONObject) request.get("model");
        String deptId = model.getJSONObject("dept").getString("id");

        //业务逻辑
        importData.forEach((k, v) -> {
            //获得value ===Excel内容
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //首行数据
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行

                if (i == 0) { //跳过首行
                    exclArr.add(headerName);
                    continue;
                }

                JSONArray lineLong = (JSONArray) excl.get(i); //当前行
                if (lineLong.size() == 0) {
                    continue; //跳过空白行
                }
                //合并2个list为一个map,KEY为首行数据，Value为当前行数据
                Map<String, String> rst = IntStream.range(0, header.size()).collect(HashMap::new,
                        (m, key) -> m.put(header.getString(key).replace(";", ""),
                                key >= lineLong.size() ? "" : (lineLong.getString(key) == null ? null : lineLong.getString(key).trim().replaceAll("[\\s]{2,}", " "))),
                        (m1, m2) -> {
                        });
                String faCardId = rst.get("卡片编码");
//                FaCard faCard = faCardRepository.findById(faCardId).get();
                Optional<FaCard> faCardOptional = faCardRepository.findOne(JpaDsl.toCriteriaByEq("id", faCardId, "dept.id", deptId));
                if(!faCardOptional.isPresent()) continue;
                FaCard faCard = faCardOptional.get();
                //用一个有序的map 封装数据, 防止乱序
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", "");
                map.put("卡片编码", faCard);
                map.put("资产类型", faCard.getFaType());
                map.put("商品编号", faCard.getProduct().getId());
                map.put("商品名称", faCard.getProduct().getName());
                map.put("部门名称", faCard.getDept().getName());
                map.put("资产去向", faCard.getFaWhereabouts());
                //将map 转换成 list 利用stream流 引用Map类的getValue方法,弄成一个list
                List<Object> valueList = new ArrayList<>(map.values());
                exclArr.add(valueList);
            }

            exclObject.put(k, exclArr);
        });
        return exclObject;
    }



    /**
     * 根据卡片id查全部
     */
    public List<FaAssetScrap> findCard(SimpleRequest request){

        String id = request.get("id");
        List<FaAssetScrap> faAssetScraps = faAssetScrapRepository.findCard(id);
        return faAssetScraps;

    }

}
